<template>
  <div class="container-image">
    <!-- 搜索区域 -->
    <el-card>
      <!-- 头部 -->
      <div slot="header">
        <!-- 自己封装的组件实现 -->
        <my-bread>素材管理</my-bread>
      </div>

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- 单选框按钮 -->
        <!-- labol属性单个按钮的值 ,当你选中点击都,这个值赋值 -->
        <el-radio-group v-model="reqParams.collect" size="small" @change="toggleList()">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <!-- 按钮 el-button -->
        <el-button style="float:right" @click="openDialog()" type="success" size="small">添加素材</el-button>
      </div>

      <!-- 图片列表 -->
      <div class="list-box">
        <div class="item-box" v-for="item in images" :key="item.id">
          <img :src="item.url" alt />
          <div class="option" v-if="!reqParams.collect">
            <span
              class="el-icon-star-off"
              @click="toggleStatus(item)"
              :class="{red:item.is_collected}"
            ></span>
            <span class="el-icon-delete" @click="deleteImage(item.id)"></span>
          </div>
        </div>
      </div>
      <!-- 分页  el-pagination -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="reqParams.per_page"
        :current-page="reqParams.page"
        @current-change="changePager"
      ></el-pagination>
    </el-card>
    <el-dialog title="上传素材" :visible.sync="dialogVisible" width="300px">
      <el-upload
        name="image"
        :headers="headers"
        :on-success="uploadSuccess"
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        :show-file-list="false"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
  </div>
</template>

<script>
import auth from "@/utils/auth";
export default {
  name: "page-image",
  data() {
    return {
      reqParams: {
        //是否获取收藏:true查询收藏图片
        collect: false,
        //页码
        page: 1,
        //每页的条数
        per_page: 10,
      },
      //素材列表
      images: [],
      // 总条数
      total: 0,
      dialogVisible: false,
      imageUrl: null,
      //上传头像
      headers: { Authorization: `Bearer ${auth.getUser().token}` },
    };
  },
  created() {
    this.getIamges();
  },
  methods: {
    //取消=时运行的函数
    //response 传的图片数据
    uploadSuccess(response) {
      //提示 +预览
      this.$message.success("上传成功");
      //把数据传个上边的imageUrl
      this.imageUrl = response.data.url;

      //3s后关闭对话框
      window.setTimeout(() => {
        this.dialogVisible = false;
        this.getIamges();
      }, 3000);
    },
    openDialog() {
      this.dialogVisible = true;
    },
    //
    async toggleStatus(item) {
      //将要 修改的状态
      const updateStatus = !item.is_collected;

      try {
        await this.$http.put(`user/images/${item.id}`, {
          collect: updateStatus,
        });
        //和当前图片状态取反即可
        this.$message.success(updateStatus ? "添加收藏成功" : "取消收藏成功");
        item.is_collected = updateStatus;
      } catch (e) {
        //提示错误
        this.$message.error(updateStatus ? "添加收藏失败" : "取消收藏失败");
      }
    },
    //删除素材
    deleteImage(id) {
      this.$confirm("此操作将永久删除该图片素材, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //点击确认,发删除请求
          try {
            //1.测试账户的数据,后台限制不能删除
            //2.请求成功 ,后台没有响应内容
            //查找到对应的id的值
            await this.$http.delete(`user/images/${id}`);
            // 同时提示条件
            this.$message.success("删除图片成功");
            // 更新渲染页面
            this.getIamges();
          } catch (e) {
            //提示删除错误
            this.$message.error("删除图片失败");
          }
        })
        .catch(() => {
          //取消后不做处理
        });
    },
    //切换全部和收藏
    toggleList() {
      //查询条件更改后回到第一页
      this.reqParams.page = 1;
      // 重新渲染
      this.getIamges();
    },
    //分页的切换
    //el-pagination 绑定change事件
    changePager(newPage) {
      //把新页码传给服务器
      this.reqParams.page = newPage;
      //在更新页面
      this.getIamges();
    },
    // 异步操作
    async getIamges() {
      //获取服务器的数据obj
      const res = await this.$http.get("user/images", {
        params: this.reqParams,
      });
      //在对象里找arr图片的数据在传给data的图片数据
      this.images = res.data.data.results;
      //在对象里找服务器的条数  在传给data的条数
      this.total = res.data.data.total_count;
    },
  },
};
</script>

<style lang="less">
.list-box {
  margin-top: 20px;
  .item-box {
    display: inline-block;
    width: 180px;
    height: 180px;
    margin-right: 60px;
    border: 1px dashed #ddd;
    position: relative;
    margin-bottom: 20px;
    img {
      display: block;
      width: 100%;
      height: 100%;
    }
    .option {
      width: 100%;
      height: 30px;
      position: absolute;
      left: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.3);
      text-align: center;
      line-height: 30px;
      span {
        color: #fff;
        margin: 0 20px;
        // 不加&解析后：span .red{} 后代选择器
        // 加上&节后后：span.red{}  交集选择器
        &.red {
          color: red;
        }
      }
    }
  }
}
</style>